package com.gp.study.tomcat.http;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpRequest;

import com.gp.study.tomcat.bean.GpServletRegistry;
import com.gp.study.tomcat.servlet.GpServlet;

public class GpRequestHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {

		if(msg instanceof HttpRequest){
			HttpRequest req = (HttpRequest) msg;
			// 转交给我们自己的request实现
			GPHttpServletRequest request = new GPHttpServletRequest(ctx,req);
			// 转交给我们自己的response实现
			GPHttpServletResponse response = new GPHttpServletResponse(ctx);
			// 实际业务处理
			String url = request.getURL();
			if(GpServletRegistry.containsKey(url)){
				GpServlet servlet = GpServletRegistry.getServlet(url);
				servlet.doService(request, response);
			}else{
				response.write("404 - Not Found");
			}
		}
		super.channelRead(ctx, msg);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		
		super.exceptionCaught(ctx, cause);
	}
	

}
